package main

import (
	"encoding/json"
	"fmt"
	"log"
)

/*
boolean         true
number          -273.15
string          "She said \"Hello, BF\""
array           ["gold", "silver", "bronze"]

object
{"year": 1980,
"event": "archery",
"medals": ["gold", "silver", "bronze"]}
*/
func main() {
	type Movie struct {
		Title  string
		Year   int  `json:"released"`
		Color  bool `json:"color,omitempty"`
		Actors []string
	}

	m1 := Movie{Title: "Casablanca", Year: 1942, Color: false, Actors: []string{"Humphrey Bogart", "Ingrid Bergman"}}
	m2 := Movie{Title: "Cool Hand Luke", Year: 1967, Color: true, Actors: []string{"Paul Newman"}}
	m3 := Movie{Title: "Bullitt", Year: 1968, Color: true, Actors: []string{"Steve McQueen", "Jacqueline Bisset"}}

	ms := []Movie{m1, m2, m3}
	fmt.Println("ms", ms)

	jsonBytes, err := json.Marshal(ms)
	if err != nil {
		log.Fatalf("JSON marshaling failed: %s", err)
	} else {
		jsonStr := string(jsonBytes)
		fmt.Println(jsonStr)
	}

	//该函数有两个额外的字符串参数用于表示每一行输出的前缀和每一个层级的缩进：
	jsonBytes2, err2 := json.MarshalIndent(ms, "", "    ")
	if err2 != nil {
		log.Fatalf("JSON marshaling failed: %s", err2)
	} else {
		jsonStr2 := string(jsonBytes2)
		fmt.Println(jsonStr2)
	}
	// str -> type
	var ms2 []Movie
	typeErr := json.Unmarshal(jsonBytes, &ms2)
	if typeErr != nil {
		fmt.Println("Error:", typeErr)
	} else {
		fmt.Println("对比1", ms2)
	}
}
